import React, { Component } from "react";
import {
  Form,
  Input,
  Select,
  Cascader,
  Col,
  Row,
  Typography,
  Radio,
  InputNumber,
  DatePicker,
  Modal,
  Table,
  message,
} from "antd";
import { getDictionaryLabel } from "../../rudexRou/OperatesCookie.js";
import { getEmpByEmpNo } from "../../api";
import moment from "moment";
import "moment/locale/zh-cn";
const { Option } = Select;
const { Search } = Input;
// import { Base64 } from 'js-base64'
class editForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [], // 选择行Key集合
      selectedRows: [], // 选择行集合
      selectedRow: {}, // 修改行数据
      isVisible: false, // 查询模态框
      total: 0,
      pageSize: 10,
      page: 1,
      dataList: [], // 表格数据
      loading: false,
      columns: [
        {
          title: "工号",
          dataIndex: "empNo",
          key: "empNo",
          width: 80,
        },
        {
          title: "姓名",
          dataIndex: "empName",
          key: "empName",
          width: 80,
        },
        {
          title: "地域",
          dataIndex: "regionNo",
          key: "regionNo",
          ellipsis: true,
          width: 100,
          render: (text) =>
            text ? getDictionaryLabel("addressConfig", text) : text,
        },
        {
          title: "部门",
          dataIndex: "orgName",
          key: "orgName",
          ellipsis: true,
          width: 180,
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
          ellipsis: true,
          width: 180,
        },
      ],
    };
  }
  componentWillMount() {
    this.props.onRef(this);
  }
  modifyFormRef = React.createRef(); //绑定修改信息表单
  onSearch = () => {
    return this.modifyFormRef.current.getFieldsValue();
  };
  getValues = () => {
    return this.modifyFormRef.current.getFieldsValue();
  };
  setValues = (data) => {
    return this.modifyFormRef.current.setFieldsValue(data);
  };
  resetFields = () => {
    this.modifyFormRef.current.resetFields();
  };
  validateFields = () => {
    return this.modifyFormRef.current.validateFields();
  };

  openSearch = () => {
    this.inputRef.blur(); // 自动失去焦点
    // this.selectFormRef.current.setFieldsValue({ searchValue: data })
    this.setState({ isVisible: true }, () => {
      // if (data) {
      //   this.searchEmpList()
      // }
    });
  };
  changeDatePicker = (data) => {
    const values = this.modifyFormRef.current.getFieldsValue();

    if (this.props.changeDate) this.props.changeDate(data, values);
  };
  selectFormRef = React.createRef(); //绑定修改信息表单
  getFields = () => {
    const getFormItem = (item) => {
      let reItem;
      if (item.type === "text") {
        reItem = ({ getFieldValue }) => {
          const value = getFieldValue(item.code) || [];
          return (
            <Typography.Text className="ant-form-text">
              {getDictionaryLabel(item.dictionaryCode, value) || value}
            </Typography.Text>
          );
        };
      }
      if (item.type === "datePicker") {
        if (item.disabled) {
          reItem = <DatePicker placeholder={item.placeholder} disabled />;
        } else {
          reItem = (
            <DatePicker
              disabledDate={item.disabledDate}
              placeholder={item.placeholder}
              onChange={() => this.changeDatePicker(item)}
            />
          );
        }
      } else if (item.type === "input") {
        if (item.disabled) {
          reItem = <Input placeholder={item.placeholder} disabled />;
        } else {
          reItem = (
            <Input placeholder={item.placeholder} maxLength={item.maxLength} />
          );
        }
      } else if (item.type === "inputNumber") {
        if (item.disabled) {
          reItem = (
            <InputNumber
              min={item.min}
              max={item.max}
              placeholder={item.placeholder}
              disabled
            />
          );
        } else {
          reItem = (
            <InputNumber
              min={item.min}
              max={item.max}
              placeholder={item.placeholder}
            />
          );
        }
      } else if (item.type === "radio") {
        reItem = (
          <Radio.Group>
            {item.options.map((item) => (
              <Radio key={item.code} value={item.code}>
                {item.label}
              </Radio>
            ))}
          </Radio.Group>
        );
      } else if (item.type === "search") {
        reItem = (
          // <Search placeholder="请输入工号或者姓名" onSearch={this.openSearch} />
          <Input
            onFocus={this.openSearch}
            ref={(input) => {
              this.inputRef = input;
            }}
          />
        );
      } else if (item.type === "number") {
        reItem = <InputNumber min={1} max={100} />;
      } else if (item.type === "select") {
        if (item.disabled) {
          reItem = (
            <Select placeholder="请选择" onChange={item.changeFn} disabled>
              {item.options.map((item) => (
                <Option key={item.code} value={item.code}>
                  {item.label}
                </Option>
              ))}
            </Select>
          );
        } else {
          reItem = (
            <Select placeholder="请选择" onChange={item.changeFn}>
              {item.options.map((item) => (
                <Option key={item.code} value={item.code}>
                  {item.label}
                </Option>
              ))}
            </Select>
          );
        }
      } else if (item.type === "multipleSelect") {
        if (item.disabled) {
          reItem = (
            <Select
              mode="multiple"
              placeholder="请选择"
              onChange={item.changeFn}
              disabled
            >
              {item.options.map((item) => (
                <Option key={item.code} value={item.code}>
                  {item.label}
                </Option>
              ))}
            </Select>
          );
        } else {
          reItem = (
            <Select
              mode="multiple"
              placeholder="请选择"
              onChange={item.changeFn}
            >
              {item.options.map((item) => (
                <Option key={item.code} value={item.code}>
                  {item.label}
                </Option>
              ))}
            </Select>
          );
        }
      } else if (item.type === "cascader") {
        reItem = <Cascader options={item.options} placeholder="请选择" />;
      }
      return reItem;
    };
    const len = this.props.formData.length;
    const children = [];
    for (let i = 0; i < len; i++) {
      children.push(
        <Col span={this.props.formData[i].half ? 12 : 24} key={i}>
          {this.props.formData[i].type === "text" ? (
            <Form.Item
              key={this.props.formData[i].code}
              label={this.props.formData[i].name}
              hidden={this.props.formData[i].hidden}
              shouldUpdate={(prevValues, curValues) =>
                prevValues[this.props.formData[i].code] !==
                curValues[this.props.formData[i].code]
              }
            >
              {getFormItem(this.props.formData[i])}
            </Form.Item>
          ) : (
            <Form.Item
              name={this.props.formData[i].code}
              label={this.props.formData[i].name}
              rules={this.props.formData[i].rules}
              hidden={this.props.formData[i].hidden}
            >
              {getFormItem(this.props.formData[i])}
            </Form.Item>
          )}
        </Col>
      );
    }
    return children;
  };
  handleOk = () => {
    this.setState({ isVisible: false, dataList: [] });
    if (this.state.selectedRows.length > 0) {
      this.props.changeUserInfo(this.state.selectedRows[0]);
    }
  };
  searchEmp = (data) => {
    this.setState({ searchValue: data }, () => {
      this.searchEmpList(true);
    });
  };
  searchEmpList = (resetPage) => {
    let params = {};
    if (resetPage === true) {
      this.setState({ loading: true, pageSize: 10, page: 1 });
      params = {
        str: this.state.searchValue.trim(),
        pageSize: 10,
        currentPage: 1,
      };
    } else {
      this.setState({ loading: true });
      params = {
        str: this.state.searchValue.trim(),
        pageSize: this.state.pageSize,
        currentPage: this.state.page,
      };
    }
    getEmpByEmpNo(params).then((response) => {
      if (response.data.code === 200) {
        if (
          response.data &&
          response.data.data &&
          response.data.data.list &&
          response.data.data.list.length > 0
        ) {
          response.data.data.list.forEach((item) => {
            if (!this.props.passPermissions) {
              item.remark = item.permissions ? "" : "无操作权限";
            } else {
              item.permissions = true;
            }
            item.orgName = item.orgCuName || item.orgBuName || item.orgBdName;
          });
          this.setState({ dataList: response.data.data.list });
          this.setState({ total: response.data.data.total });
        } else {
          message.warning("没找到相关人员信息!");
        }
      } else {
        message.error("查询人员信息错误!");
      }
      this.setState({ loading: false });
    });
  };
  handleCancel = () => {
    // this.selectFormRef.current.setFieldsValue({ searchValue: data })
    this.setState({ isVisible: false, dataList: [] ,total:0});
  };
  //修改页数changePage
  changePage = (page, pageSize) => {
    this.setState(
      {
        page,
        pageSize,
      },
      () => {
        this.searchEmpList(false);
      }
    );
  };
  render() {
    const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        });
      },
      getCheckboxProps: (record: DataType) => ({
        disabled: record.permissions === false, // Column configuration not to be checked
        name: record.name,
      }),
    };
    return (
      <div>
        <Form
          labelCol={{ style: { width: 150 } }}
          ref={this.modifyFormRef}
          onFinish={this.onFinish}
          size="small"
        >
          <Row gutter={24}>{this.getFields()}</Row>
        </Form>
        <Modal
          title="选择员工"
          type="primary"
          okText="确认"
          cancelText="取消"
          width="1000px"
          visible={this.state.isVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          destroyOnClose={true}
          forceRender={true}
        >
          <div>
            <div>
              <Form
                ref={this.selectFormRef}
                name="updateInfo"
                onFinish={this.onUpdateFinish}
              >
                <Form.Item name="searchValue" label="请输入工号/姓名">
                  <Search
                    placeholder="请输入工号/姓名"
                    onSearch={this.searchEmp}
                  />
                </Form.Item>
              </Form>
            </div>
            <div>
              <Table
                rowSelection={{
                  type: "radio",
                  ...rowSelection,
                }}
                loading={this.state.loading}
                dataSource={this.state.dataList}
                bordered
                columns={this.state.columns}
                rowKey={(record) => record.empNo}
                pagination={{
                  total: this.state.total,
                  pageSize: this.state.pageSize,
                  current: this.state.page,
                  onChange: this.changePage,
                  showTotal: (total) => "共 " + total + " 条",
                }}
              ></Table>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default editForm;
